
import { getWorktypes } from '@/api'
const state = {
  agent: '',
  os: '',
  version: '',
  device: '',
  menuButton: '',
  navbarHeight: 64,
  phone: null,
  workTypes: []
}

const mutations = {
  SET_DEVICE: (state, data) => {
    state.device = data
  },
  SET_MENU_BUTTON: (state, data) => {
    state.menuButton = data
  },
  SET_NAVBAR_HEIGHT: (state, data) => {
    state.navbarHeight = data
  },
  SET_PHONE: (state, data) => {
    state.phone = data
  },
  SET_WORK_TYPES: (state, data) => {
    state.workTypes = data
  }
}

const actions = {
  setPhone ({ commit }, data) {
    commit('SET_PHONE', data)
  },
  setDevice ({ commit }, data) {
    console.log('setDevice 每次调用？？？', data)
    commit('SET_DEVICE', data)
    const {statusBarHeight, platform} = data
    let platformReg = /ios/i
    const navBarHeight = platformReg.test(platform) ? 44 + statusBarHeight : 48 + statusBarHeight
    commit('SET_NAVBAR_HEIGHT', navBarHeight)
  },
  setMenuButton ({ commit }, data) {
    console.log('setMenuButton', data)
    commit('SET_MENU_BUTTON', data)
  },
  setWorkTypes ({ commit }, data) {
    if (data && data.length > 0) {
      wx.setStorageSync('workTypes', data)
      commit('SET_WORK_TYPES', data)
    } else {
      const workTypes = wx.getStorageSync('workTypes')
      if (workTypes.length > 0) {
        commit('SET_WORK_TYPES', workTypes)
      } else {
        getWorktypes().then(response => {
          if (response.length > 0) {
            wx.setStorageSync('workTypes', response)
            commit('SET_WORK_TYPES', response)
          }
        })
      }
    }
  },
  initSetWorkTypes ({ commit }, data) {
    commit('SET_WORK_TYPES', data)
  },
  getWorkTypes ({ commit }) {
    return new Promise((resolve, reject) => {
      if (state.workTypes.length > 0) {
        console.log('getWorkTypes from state.')
        resolve(state.workTypes)
      } else {
        const workTypes = wx.getStorageSync('workTypes')
        if (workTypes.length > 0) {
          commit('SET_WORK_TYPES', workTypes)
          console.log('getWorkTypes from getStorageSync.')
          resolve(workTypes)
        } else {
          console.log('wechat authing........')
          getWorktypes().then(response => {
            if (response.length > 0) {
            // this.setWorkTypes(response)
              commit('SET_WORK_TYPES', response)
            }
            console.log('getWorkTypes from request.')
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        }
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
